package com.gm.commonlib.base.baseui.baseactivity;


import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.JsResult;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;

import com.gm.commonlib.R;
import com.gm.commonlib.base.baseui.baseFragment.BaseFragment;
import com.gm.commonlib.views.toast.ToastUtil;


/**
 * @author ：hck
 */

public abstract class BaseWebViewFragment extends BaseFragment {
    public static String URL = "url";
    public static String TITLE = "title";
    private FrameLayout mTitle;
    public WebView mViewView;
    private FrameLayout mButtomView;
    WebSettings webSettings;

    @Override
    protected void onCreateContentBody(ViewGroup parent) {
       View view= LayoutInflater.from(context).inflate(R.layout.activity_webview,parent);
        mViewView = view.findViewById(R.id.webview);
        mButtomView = view.findViewById(R.id.buttom);
        mTitle = view.findViewById(R.id.titleFly);
        setCache(WebSettings.LOAD_NO_CACHE);
        initVewView(mViewView);
        onCreateTitle(mTitle);
        intViewViewSetting(mViewView);
        onCreateButtomView(mButtomView);
    }


    public void setUserAgent(String userAgent){
        String userAgents = webSettings.getUserAgentString();
        webSettings.setUserAgentString( userAgents+userAgent);

    }

    public void onCreateTitle(FrameLayout mTitle) {

    }


    public void initVewView(WebView mViewView) {
        mViewView.clearCache(true);
        mViewView.clearHistory();
        mViewView.clearFormData();
    }

    public void onCreateButtomView(FrameLayout view) {

    }

    public void loadStart() {

    }

    public void loadFinish() {

    }


    public void intViewViewSetting(final WebView mViewView) {
//声明WebSettings子类
        webSettings = mViewView.getSettings();
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        webSettings.setAllowFileAccess(true);

//如果访问的页面中要与Javascript交互，则webview必须设置支持Javascript
        webSettings.setJavaScriptEnabled(true);
        //支持
        webSettings.setDomStorageEnabled(true);

//设置自适应屏幕，两者合用
        webSettings.setUseWideViewPort(true); //将图片调整到适合webview的大小
        webSettings.setLoadWithOverviewMode(true); // 缩放至屏幕的大小
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);

//缩放操作
        webSettings.setSupportZoom(true); //支持缩放，默认为true。是下面那个的前提。
        webSettings.setBuiltInZoomControls(true); //设置内置的缩放控件。若为false，则该WebView不可缩放
        webSettings.setDisplayZoomControls(false); //隐藏原生的缩放控件
        webSettings.setBlockNetworkImage(false);//解决图片不显示
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        webSettings.setUseWideViewPort(true);
        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        webSettings.setLoadWithOverviewMode(true);
//其他细节操作
        webSettings.setAllowFileAccess(true); //设置可以访问文件
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true); //支持通过JS打开新窗口
        webSettings.setLoadsImagesAutomatically(true); //支持自动加载图片
        webSettings.setDefaultTextEncodingName("utf-8");//设置编码格式
        mViewView.setWebViewClient(new WebViewClient() {
                                       @Override
                                       public void onPageFinished(WebView view, String url) {
                                           super.onPageFinished(view, url);
                                           hidLoadingDialog();
                                           loadFinish();

                                       }

                                       @Override
                                       public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                                           super.onReceivedError(view, errorCode, description, failingUrl);
                                           ToastUtil.showToast(description);

                                       }

                                       @Override
                                       public boolean shouldOverrideUrlLoading(WebView view, String url) {
                                           view.loadUrl(url);
                                           return true;
                                       }

                                       @Override
                                       public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                                           handler.proceed();
                                           super.onReceivedSslError(view, handler, error);
                                       }
                                   }


        );
        /**
         * 支持弹窗
         */
        mViewView.setWebChromeClient(new WebChromeClient() {
                                         @Override
                                         public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
                                             ToastUtil.showToast(message);
                                             mViewView.reload();
                                             return true;
                                         }
                                     }
        );

    }

    public void setTextSize(WebSettings.TextSize size) {
        webSettings.setTextSize(size);
    }

    public void setZoom(int size) {
        webSettings.setTextZoom(size);
    }

    public void setCache(int mode) {
        //优先使用缓存:
        mViewView.getSettings().setCacheMode(mode);
        //缓存模式如下：
        //LOAD_CACHE_ONLY: 不使用网络，只读取本地缓存数据
        //LOAD_DEFAULT: （默认）根据cache-control决定是否从网络上取数据。
        //LOAD_NO_CACHE: 不使用缓存，只从网络获取数据.
        //LOAD_CACHE_ELSE_NETWORK，只要本地有，无论是否过期，或者no-cache，都使用缓存中的数据。
    }

    /**
     * //方式1. 加载一个网页：
     * webView.loadUrl("http://www.google.com/");
     * <p>
     * //方式2：加载apk包中的html页面
     * webView.loadUrl("file:///android_asset/test.html");
     *
     * @param
     */
    public void loadUrl(String url) {
        showLoadingDialog();
        if (!TextUtils.isEmpty(url)) {
            mViewView.loadUrl(url);
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (mViewView!=null){
            mViewView.destroy();
        }

    }
}
